<template>
  <div class="updata-photo">
    <img :src="img" class="img" ref="img" />

    <div class="box">
      <div class="cancel" @click="$emit('close')">取消</div>
      <div class="confirm" @click="onConfirm">完成</div>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updataPhotoAPI } from '@/api/User.js'
export default {
  name: 'updataPhoto',
  props: {
    img: {
      type: [Object, String],
      required: true
    }
  },
  data() {
    return {
      cropper: null
    }
  },
  mounted() {
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false,
      movable: true
    })
    // console.log(cropper)
  },
  methods: {
    onConfirm() {
      this.cropper.getCroppedCanvas().toBlob(blob => {
        this.updataUsersPhoto(blob)
      })
    },
    async updataUsersPhoto(blob) {
      this.$toast.loading({
        message: '保存中...',
        forbidClick: true, //禁止背景点击
        duration: 0
      })

      try {
        const formData = new FormData()
        formData.append('photo', blob)

        const { data } = await updataPhotoAPI(formData)
        // console.log(data)
        // 关闭弹层
        this.$emit('close')
        // 更新视图
        this.$emit('update-photo', data.data.photo)
        this.$toast.success('更新成功')
      } catch (err) {
        this.$toast.fail('更新失败，请稍后重试！')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.img {
  max-width: 100%;
  display: block;
}
.updata-photo {
  background-color: #000;
  height: 100%;
  .box {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    .cancel,
    .confirm {
      width: 90px;
      height: 90px;
      font-size: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
    }
  }
}
</style>
